import json
import logging
import os.path
import time

import pandas as pd
from websocket import create_connection

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S ', level=logging.INFO)
logger = logging.getLogger(__name__)

# 定义文件输入路径
# excel_file_path = r"Case1.xlsx"
# excel_file_path = r"算例3.xls"
# excel_file_path = r"算例4.xls"
# excel_file_path = r"算例4.xls"
excel_file_path = r"算例5.xls"

# WebSocket服务器的URL
websocket_url = "ws://10.1.16.50:11051/ws/dynamic"  # 替换为实际的WebSocket服务器URL

base_file_name = os.path.basename(excel_file_path)
message = str({'uName': "cupb", 'pName': base_file_name})

# 开始计时
start_time = time.time()

# 创建WebSocket连接，并指定on_message回调函数
ws = create_connection(websocket_url)
connection_status = ws.recv()  # 接收服务器回复的消息1
str = ws.getstatus()  # 获取连接状态

bytes_sent1 = ws.send(message)
initialization_status = ws.recv()  # 接收服务器回复的开始初始化和接收的文件名
initialization_finish_check = ws.recv()  # 接收服务器回复的完成初始化信息

# 暂停一下
time.sleep(0.5)

df_datas = []
df_data0 = pd.DataFrame()
# 定义输出变量名称
series = ['myProfile', 'myProfileE', 'myProfileHl', 'myProfileP', 'myProfileT', 'myProfileTg', 'myProfileTl',
          'myProfileV', 'myProfileVg', 'myProfileVl', 'myCumVolL']
myProfile, myProfileE, myProfileHl, myProfileP, myProfileT \
    , myProfileTg, myProfileTl, myProfileV, myProfileVg, myProfileVl, myCumVolL = {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}
seriesVars = [myProfile, myProfileE, myProfileHl, myProfileP, myProfileT,
              myProfileTg, myProfileTl, myProfileV, myProfileVg, myProfileVl, myCumVolL]

totalT = 6000

if bytes_sent1 != -1:
    logger.info(message + f"send计算模型指定成功: {bytes_sent1}")

    bytes_sent2 = ws.send("simStart")
    last_iteration_time = []  # 初始化上一次迭代时间的变量
    if bytes_sent2 != -1:
        logger.info(f"开始计算: {bytes_sent2}")
        i = 1
        while True:
            result4 = ws.recv()
            result4j = json.loads(result4)  ##获取json格式的数据结果
            logger.info(result4j)

            data = result4j['data']
            # print(result4)

            if len(data) == 0:
                logger.error("计算错误，无结果")
                bytes_sent4 = ws.send("simStop")
                if bytes_sent4 != -1:
                    logger.info("计算已停止")
                break

            timeRecord = format(data['myCostT'], '.3f')

            for v in range(len(seriesVars)):
                if series[v] not in data:
                    seriesVars[v][timeRecord] = []
                else:
                    seriesVars[v][timeRecord] = data[series[v]]

            # logger.error("目前计算到" + str(data['myCostT']))
            i = i + 1

            # 判断上一次迭代时间与本次迭代时间是否相同，如果相同则证明计算发散，需要停止服务器计算
            if data['myCostT'] == last_iteration_time:
                ws.send("simStop")
                logger.info("计算已结束")
                break
            else:
                # 如果上一次迭代时间与本次迭代时间不同，则将本次迭代时间赋值为上次迭代时间，并进行下一次运算
                last_iteration_time = data['myCostT']

            if data['myCostT'] >= totalT:
                ws.send("simStop")
                logger.info("计算已结束")
                break
    else:
        logger.info(" simStart 开始计算失败")

else:
    print(message + "send 中 计算模型指定失败")

# 关闭WebSocket连接
ws.close()

end_time = time.time()
execution_time = end_time - start_time

for v in range(len(seriesVars)):
    df_data = pd.DataFrame(seriesVars[v])
    df_datas.append(df_data)

excel_file_path = r"结果.xls"

# 保存模拟结果
with pd.ExcelWriter(excel_file_path, engine='xlsxwriter') as writer:
    for i in range(len(df_datas)):
        df_datas[i].to_excel(writer, sheet_name=series[i], index=False)

    logger.error('结果已输出至' + excel_file_path)

print(f"算例运行时间：{execution_time}秒")
